<template>
  <div id="container" ref="canvasref">
  </div>
</template>
<!-- <script src="./static/SharkViewer/lib/three.min.js"></script> -->
<!-- <script src="./static/SharkViewer/lib/shark_viewer.js"></script> -->
<script>
// import {THREE} from "../../static/SharkViewer/lib/three.min.js"
// import * as THREE from "three";
// import {sharkViewer} from "../../static/SharkViewer/lib/shark_viewer.js"
// const THREE = require('three')
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader";
// import SharkViewer, { swcParser } from sharkViewer;

import axios from 'axios'
import { globalBus } from './globalBus';

 const hex2Rgba = (bgColor, alpha = 1) => {
  let color = bgColor.slice(1); // 去掉'#'号
  let rgba = [
    parseInt("0x" + color.slice(0, 2)),
    parseInt("0x" + color.slice(2, 4)),
    parseInt("0x" + color.slice(4, 6)),
    alpha
  ];
  // return "rgba(" + rgba.toString() + ")";
  return rgba;
};

export default {
  data: () => ({
    controls: {
      scene: null,
      camera: null,
      renderer: null,
      // rotationSpeed: 0.02
    },
    controller: null
  }),
  created() {
    var controller = {
      BackgroundColor: 0x000000,
      AllSoma: false,
      SomaSize:80
    };
    this.controller = controller;
    const gui = new dat.GUI();
    gui.domElement.style.position = 'absolute';
    gui.domElement.style.right = '10px';
    gui.domElement.style.top = '80px';
    var h = gui.addFolder("Setting");
    h.addColor(controller, 'BackgroundColor').onChange(this.update);
    h.add(controller, 'AllSoma').onChange(this.allsoma);
    h.add(controller, 'SomaSize').onChange(this.update);
    gui.addFolder("Properties");
    // debugger
    this.$nextTick(() => {
      this.init()
    })
  },
  mounted() {

    window.onresize = () => {
        const width = this.$refs.canvasref.clientWidth;
        const height = this.$refs.canvasref.clientHeight;
        window.s.setSize(width, height);
        window.s.render();

      },
      globalBus.$on("addRegion", region => {
        console.log(region[0], region[1])
        axios.get('./static/allobj/' + region[0] + ".obj")
          .then(res => {
            // debugger
            if (!s.compartmentLoaded(region[1]))
              s.loadCompartment(region[1], '#' + region[2], res.data);
            //将返回值赋给上述已定义的本地变量
          })
      }),
      globalBus.$on("removeRegion", region => {
        console.log(region[0], region[1])
        // debugger
        s.unloadCompartment(region[1])
        window.s.trackControls.update()

      }),
      globalBus.$on("getNeuron", neuron => {
        // console.log(neuron);
        var sample = neuron[0];
        var name = neuron[1];
        var color = neuron[2];
        var neuronname = sample + name;
        if (!window.s.neuronLoaded(neuronname)) {

          let swc;
          axios.get('api/user/getSWC?sampleid='+sample+'&&neuronid='+name, {
            neuron
          }).then(res => {

            swc = sharkViewer.swcParser(res.data);
            console.log("load " + neuronname)
            window.s.loadNeuron(neuronname, color, swc, true, false, true);

            var cells = new THREE.BufferGeometry();
            let vertex = [];
            let colors = [];
            for(let i=0;i<Object.keys(swc).length;i++){
            // Object.keys(swc).forEach(node => {
              var node = swc[i+1]
              vertex.push(node.x)
              vertex.push(node.y)
              vertex.push(node.z)
              var rgb = hex2Rgba(color)
              // debugger
              colors.push(rgb[0]);
              colors.push(rgb[1]);
              colors.push(rgb[2]);
              break;
            }

            cells.setAttribute("position", new THREE.Float32BufferAttribute(vertex, 3))
            cells.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3))

            var loader = new THREE.TextureLoader()
            loader.load("./static/test.png",function(texture){
              var material = new THREE.PointsMaterial({
                vertexColors: THREE.VertexColors,
                map: texture,
                blending: THREE.AdditiveBlending,
                depthTest: false,
                transparent: false,
                opacity: 0.8,
                size: 100.0
              });


              var points = new THREE.Points(cells, material);
              points.name = 'allsoma';

              window.s.scene.add(points);
            });
            window.s.render();
            window.s.trackControls.update()
          });
        }

      }),
      globalBus.$on("removeNeuron", neuron => {
        var sample = neuron[0];
        var name = neuron[1];
        var neuronname = sample + name;
        // debugger
        if (window.s.neuronLoaded(neuronname)) {
          console.log("remove " + neuronname)

          window.s.unloadNeuron(neuronname);
          window.s.trackControls.update()
        }
      }),
      globalBus.$on("selectNeuron", neuron => {
        if (window.s.neuronLoaded(neuron[0] + neuron[1])) {
          const r = window.s.scene.getObjectByName(neuron[0] + neuron[1]);
          // debugger
          for (var i = r.parent.children.length - 1; i >= 0; i--) {
            if (r.parent.children[i].isNeuron) {
              r.parent.children[i].children[0].material.uniforms.select = { value: 0 };
              r.parent.children[i].children[0].material.uniforms.selectcount = { value: 1 };
            }
          }
          r.children[0].material.uniforms.selectcount = { value: 1 };
          r.children[0].material.uniforms.select = { value: 1 };
          window.s.trackControls.update()
        }
      }),
      globalBus.$on("setNeuronColor", neuron => {
        var sample = neuron[0];
        var name = neuron[1];
        var neuronname = sample + name;
        // debugger
        if (window.s.neuronLoaded(neuronname)) {
          console.log("set Neuron Color " + neuronname)

          var n = window.s.scene.getObjectByName(neuronname)
          // debugger
          n.children[0].material.uniforms.color = { value: new THREE.Color(neuron[2]) };
          window.s.trackControls.update()
        }
      })
  },
  methods: {
    randomHexColor() { //随机生成十六进制颜色
      return '#' + ('00000' + ((Math.random() * 0x1000000 << 0)).toString(16)).substr(-6);
    },
    update() {
      window.s.setBackground(this.controller.BackgroundColor);
      var n = window.s.scene.getObjectByName("allsoma");
      if(n)
        n.material.size = this.controller.SomaSize;
      window.s.trackControls.update();

    },
    allsoma(value) {
      console.log("allsoma", value)
      if (value) {
        axios.post('api/user/getAllSoma').then(res => {
          var cells = new THREE.BufferGeometry();
          let vertex = [];
          let colors = [];

          for (var i = res.data.length - 1; i >= 0; i--) {

            vertex.push(res.data[i].somax);
            vertex.push(res.data[i].somay);
            vertex.push(res.data[i].somaz);
            // debugger
            var color = new THREE.Color(this.randomHexColor());
            colors.push(color.r);
            colors.push(color.g);
            colors.push(color.b);
            // debugger
          }
          cells.setAttribute("position", new THREE.Float32BufferAttribute(vertex, 3))
          cells.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3))
          debugger
          var loader = new THREE.TextureLoader()
          loader.load("./static/test.png",function(texture){
          debugger
          var material = new THREE.PointsMaterial({
            vertexColors: THREE.VertexColors,
            map: texture,
            blending: THREE.AdditiveBlending,
            depthTest: false,
            transparent: true,
            opacity: 0.8,
            size: 100.0
          });


          var points = new THREE.Points(cells, material);
          points.name = 'allsoma';

          window.s.scene.add(points);
          window.s.render();
          window.s.trackControls.update();
            
          });



        });
      } else {

        window.s.unloadCompartment("allsoma");
        window.s.trackControls.update()
      }
    },
    onSelectNode(e, t, n) {
      // debugger
      for (var i = t.object.parent.parent.children.length - 1; i >= 0; i--) {
        if (t.object.parent.parent.children[i].isNeuron) {
          t.object.parent.parent.children[i].children[0].material.uniforms.select = { value: 0 };
          t.object.parent.parent.children[i].children[0].material.uniforms.selectcount = { value: 1 };
        }
        // console.log(.name)
      }
      t.object.material.uniforms.select = { value: 1 };
      window.s.trackControls.update()
      globalBus.$emit("highlightNeuron", [e.slice(0, -7), e.slice(-7)])
    },
    init() {

      let s = new sharkViewer.default({
        animated: false,
        mode: 'skeleton',
        dom_element: document.getElementById('container'),

        showAxes: 10000,
        maxVolumeSize: 50000,
        backgroundColor: 0x000000,
        // cameraChangeCallback: () => {},
        on_select_node: (e, t, n) => this.onSelectNode(e, t, n),
      });
      window.s = s;
      s.init();
      s.animate();
      // s.addAxes();

      s.showAxes && (s.axesCamera.position.copy(s.camera.position),
        s.axesCamera.position.sub(s.trackControls.target),
        s.axesCamera.position.setLength(300),
        s.axesCamera.lookAt(s.axesScene.position));


      axios.get('./static/allobj/997.obj')
        .then(res => {
          // debugger
          s.loadCompartment('root', '#ffffff', res.data); //
          s.centerCameraAroundCompartment(s.scene.getObjectByName('root')); //将返回值赋给上述已定义的本地变量
          window.s.trackControls.update()
        })


      s.render();


    },


  }
}

</script>
<style scoped>
div {

  height: 100%;

  background: #000000;
  color: #ffffff;
}

</style>
